package io.gitee.thinkbungee.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.gitee.thinkbungee.bean.ResponseResult;
import io.gitee.thinkbungee.service.GeneratorService;
import io.gitee.thinkbungee.utils.Query;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author chenyichang
 * @date 2022/3/8
 */
@RestController
@RequestMapping("/generator")
public class GeneratorController {

    @Autowired
    private GeneratorService generatorService;

    /**
     * 列表
     *
     * @param params
     * @return
     */
    @GetMapping("/list")
    public ResponseResult list(@RequestParam Map<String, Object> params) {
        Page page = generatorService.queryList(new Query(params));
        return ResponseResult.success(page);
    }

    /**
     * 生成代码
     */
    @GetMapping("/code")
    public void code(String tables, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(tables)) {
            return;
        }

        byte[] data = generatorService.generatorCode(tables.split(","));

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
